import React, { useMemo } from 'react';
import { Button, Row, Col, Input, Form, message } from 'antd';
import { connect } from 'react-redux';
import FormItem from '../../../components/FormItem';
import services from '../../../services/api';
import DeptSelect from '../../../components/DeptSelect';
import './index.less';

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

function toTemplate(props) {
  // const [hasRight, setHasRight] = useState([]); // 可见部门
  const deptArr = { ids: [-1], name: ['所有部门'] };
  // useEffect(() => {
  //   getDeptAll();
  // }, []);
  const { name, strategy_id, remark } = props.value;
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const params = {
          name: values.name,
          remark: values.remark,
          dept_ids: values.dept_ids.map((item) => item.value),
          strategy_id: strategy_id,
        };
        services.template
          .create(params)
          .then((res) => {
            if (!res.code) {
              message.success(res.msg);
              props.closeModel && props.closeModel();
            } else {
              message.error(res.msg);
            }
          })
          .catch((err) => {
            message.error(err);
          });
      }
    });
  }
  // 部门id变化
  // function deptSelectChange(data) {
  //   if (!data.length) {
  //     window.setTimeout(() => {
  //       props.form.setFieldsValue({ dept_ids: [] });
  //     });
  //     return;
  //   }
  //   const ltg = data.length - 1;
  //   let depArr = {};
  //   if (data[ltg].value === -1) {
  //     depArr = { ids: [-1], name: ['所有部门'] };
  //   } else {
  //     depArr = {
  //       ids: data.reduce((pre, next) => {
  //         if (next.value !== -1) {
  //           pre.push(next.value);
  //         }
  //         return pre;
  //       }, []),
  //       name: data.reduce((pre, next) => {
  //         if (next.label !== '所有部门') {
  //           pre.push(next.label);
  //         }
  //         return pre;
  //       }, []),
  //     };
  //   }
  //   const newDepArr = depArr.ids.map((it, index) => {
  //     const obj = {
  //       value: it,
  //       label: depArr.name[index],
  //     };
  //     return obj;
  //   });
  //   window.setTimeout(() => {
  //     props.form.setFieldsValue({ dept_ids: newDepArr });
  //   });
  // }
  // 获取可见部门列表
  // function getDeptAll() {
  //   services.dept.hasRight().then((res) => {
  //     if (res.code === 0) {
  //       if (res.data.length && !res.data[0].dept_id) {
  //         res.data.dept_id = -1;
  //       }
  //       setHasRight(res.data);
  //     }
  //   });
  // }
  const DeptSelectNode = useMemo(
    () =>
      DeptSelect({
        treeCheckable: true, // 是否多选
        treeCheckStrictly: true, // 多选时是否取消父子关联
        deptTree: props.depts, // 全部部门数据
        deptArr: deptArr, // 当前部门数据
        hasRight: true, // 是否需要权限展示
        // onChange: (data) => {
        //   deptSelectChange(data);
        // },
        rules: [{ required: true, message: '请选择可见部门' }],
        // nodeDisabled: (item) => !item.dept_id, // 节点禁选
        layout: layout,
        form: props.form,
      }),
    [props.depts]
  );
  const getFormItems = () => {
    // const { databaseName, databaseType = 'mysql', ipPort, userName, password, remark } = value || {};
    return [
      {
        label: {
          label: '模板名称',
          ...layout,
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [
            { required: true, message: '请输入模板名称' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='请输入模板名称' />,
      },
      {
        label: {
          label: '描述',
          ...layout,
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: <Input.TextArea placeholder='请添加描述' />,
      },
      DeptSelectNode,
    ].filter(Boolean);
  };
  return (
    <Form layout='horizontal' onSubmit={() => false}>
      <p className='template-title'>{`您正在把【${name}策略】转为模版`}</p>
      <Row type='flex'>
        {getFormItems().map((item) => {
          return (
            <Col span={24} key={item.name}>
              <FormItem form={props.form} item={item} colNum={1} />
            </Col>
          );
        })}
        <div className='template-form-btn'>
          <Button type='primary' autoFocus={true} onClick={handleSubmit} className='login-form-button'>
            确定
          </Button>
          <Button className='login-form-button' onClick={() => props.closeModel()}>
            取消
          </Button>
        </div>
      </Row>
    </Form>
  );
}
function mapStateToProps(state) {
  return {
    depts: state.global.depts,
  };
}
export default connect(mapStateToProps)(Form.create()(toTemplate));
